package com.ys.controller.api.purchase;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgPurchasePayment;
import com.ys.entity.sys.YsCol;
import com.ys.service.purchase.TcgPurchasePaymentService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-08-08
 * @Description: 采购付款控制层
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/inter/tcgPurchasePayment")
public class ApiInterTcgPurchasePaymentController {

    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchasePaymentController.class);

    @Autowired
    private TcgPurchasePaymentService tcgPurchasePaymentService;

    //菜单id
    private Long menuId = MenuId.TCG_PurchasePayment;

    @Autowired
    private CommonApiService<TcgPurchasePayment> commonApiService;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchasePayment:view";
    private final String PERMISSIONS_ADD = "tcgPurchasePayment:add";


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @param cond
     * @return
     */
    public TcgPurchasePayment setSeachSql(TcgPurchasePayment cond){
                 cond.addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
                .addField("FORMAT(Ysp.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
                .addField("FORMAT(A.createTime, 'yyyy-MM-dd hh:mm:ss') AS createTime1")//创建时间
                .addLeftJoin("TCW_PartnerBankInfo PB on PB.id = A.PartnerBankInfoId")//供应方公司
                .addField("PB.PartnerName partnerBankInfoName")
                .addLeftJoin("TB_CompanyBankInfo cbi ON cbi.id = A.CompanyBankInfoId")//购买方公司银行
                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = cbi.CompanyInfoVid")//购买方公司
                .addField("CI.Vname companyName,CI.vname companyBankInfoName")//公司信息
                 .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                 .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")

                 .addLeftJoin("TCG_PurchasePaymentItem ppi ON ppi.pBid = A.bid")//采购付款单子表
                 .addField("ppi.subPaidNum AS subPaidNum")//子件已付款数量
                 .addField("ppi.subThisPaidNum AS subThisPaidNum")//子件本次付款数量
                 .addLeftJoin("TCG_PurchaseContractItem S ON S.id = ppi.purchaseContractItemId")//合同单子表
                 .addLeftJoin("TCG_PurchaseContract AA ON AA.bid = S.pBid ")//预约采购管理表

//                 .addLeftJoin("TCG_PurchaseAppointOrder O ON O.Id = AA.PurchaseAppointOrderId ")//预约采购管理表

                 .addField("S.SubBomNumber AS subBomNumber")//子件BOM数量
                 .addField("S.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                 .addField("S.SubPurchasePrice AS subPurchasePrice")//子件采购单价
                 .addField("S.PurchaseTotalPrice AS purchaseTotalPrice")//子件采购总价

                 .addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = S.OrderProductComponentId")//预约采购管理子件表
                 .addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
                 .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
                 .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                 .addField("PPC.Bid AS purchaseAppointOrderBid")//预约采购单单号
                 .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                 .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                 .addField("PC.ProductCode AS productCode")//商品编码
                 .addField("PC.ProductName AS productName")//商品名称
                 .addField("PC.CodeMerge AS codeMerge")//合并商品编码
                 .addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
                 .addField("C.SubCode AS subCode")//子件编码
                 .addField("C.SubName AS subName")//子件名称
                 .addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
                 .addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量
                 .addField("AA.bid purchaseContractBid")
                 .addField("FORMAT(AA.createTime, 'yyyy-MM-dd HH:mm:ss')  _ys_CreateTime")
                 .addField("S.id purchaseContractItemId")
                 .addField("S.subPaymentNum")
        ;
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }

    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchasePayment cond, String conditions
    ){
        try {
            String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
            if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
                cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
            }
            cond = setSeachSql(cond);

            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcgPurchasePaymentService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcgPurchasePaymentService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/toDel")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {

            return tcgPurchasePaymentService.del(id);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            TcgPurchasePayment entity = new TcgPurchasePayment().setId(id).queryFirst();
            return tcgPurchasePaymentService.flowPass(entity.getBid(), ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("流转出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 流转退回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchasePayment entity = new TcgPurchasePayment().setId(id).queryFirst();
            return tcgPurchasePaymentService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("退回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchasePayment entity = new TcgPurchasePayment().setId(id).queryFirst();
            return tcgPurchasePaymentService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchasePayment cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
            if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
                cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
            }

            cond = setSeachSql(cond);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcgPurchasePayment> util = new ExportExcelUtils<>(new TcgPurchasePayment());
            String toFilePath = util.exportExcel(listData, listField, "采购付款报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 采购退款
     */
    @RequestMapping("/cgtk")
    @ResponseBody
    public R cgtk(HttpServletRequest request, Long id, Long capitalClaimSonId){
        try {
            return tcgPurchasePaymentService.cgtk(id, capitalClaimSonId);
        } catch (Exception e) {
            logger.error("采购退款出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }
}
